package jgl.vajra.kingkong.widget.push;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import jgl.vajra.kingkong.manager.AccountManager;
import jgl.vajra.kingkong.widget.bean.JPushBean;
import jgl.vajra.kingkong.widget.manager.RxJavaHttpManager;
import jgl.vajra.kingkong.widget.manager.SPManager;
import jgl.vajra.kingkong.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.kingkong.widget.retrofithelper.rxsubscriber.CommonObserver;
import jgl.vajra.kingkong.widget.utils.UIUtils;
import com.orhanobut.logger.Logger;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import androidx.fragment.app.FragmentActivity;
import cn.jpush.android.api.JPushInterface;

public class JPushManager {

    /**
     * 消息Id
     **/
    private static final String KEY_MSGID = "msg_id";
    /**
     * 该通知的下发通道
     **/
    private static final String KEY_WHICH_PUSH_SDK = "rom_type";
    /**
     * 通知标题
     **/
    private static final String KEY_TITLE = "n_title";
    /**
     * 通知内容
     **/
    private static final String KEY_CONTENT = "n_content";
    /**
     * 通知附加字段
     **/
    private static final String KEY_EXTRAS = "n_extras";

    /**
     * 推送数据
     */
    public final String JPUSH_DATA = "jpushData";

    /**
     * LAUNCHER 页面 Class
     */
    private Class LAUNCHER_CLASS = null;

    public void addCourseTagIdToJPushTag() {
        if (!AccountManager.getInstance().isLogin()) return;
        JPushInterface.cleanTags(UIUtils.getContext(), 10086);
        RetrofitJsonManager.getInstance().getApiService().getMyCourseTagId().compose(RxJavaHttpManager.applyTransformer()).subscribe(new CommonObserver<List<String>>() {
            @Override
            public void onNext(List<String> courseTagIds) {
                super.onNext(courseTagIds);
                Set<String> courseTagIdSet = new HashSet<>(courseTagIds);
                JPushInterface.setTags(UIUtils.getContext(), 10086, courseTagIdSet);
            }
        });
    }

    public void onOpenPush() {
        boolean openPushTag = SPManager.JPushData.getOpenPushTag();
        if (openPushTag) {
            JPushInterface.resumePush(UIUtils.getContext());
        } else {
            JPushInterface.stopPush(UIUtils.getContext());
        }
    }

    private static class JPushManagerSingleton {
        private static final JPushManager INSTANCE = new JPushManager();

    }

    public static JPushManager getInstance() {
        return JPushManager.JPushManagerSingleton.INSTANCE;
    }

    private JPushManager() {

    }

    /**
     * 处理推送操作
     *
     * @param fragmentActivity
     * @param intent           获取传递的数据
     */
    public void handlerPushOp(FragmentActivity fragmentActivity, Intent intent) {
        if (LAUNCHER_CLASS == null) {
            return;
        }
        //消息ID
        String pushMsgId = null;
        //下发通道
        String romType = null;
        //标题
        String pushTitle = null;
        // 推送内容
        String pushContent = null;
        //附加字段
        String pushExtras = null;
        // 判读是否存在数据
        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras == null) return;
            pushMsgId = extras.getString("msg_id");
            romType = extras.getString("rom_type");
            pushTitle = extras.getString("n_title");
            pushContent = extras.getString("n_content");
            pushExtras = extras.getString("n_extras");

            SPManager.JPushData.saveJPushData(pushMsgId, romType, pushTitle, pushContent, pushExtras);
            Logger.e("jpushManager  is pushData save ");

        }


        // 关闭当前页面
        fragmentActivity.finish();
        // =================  进行跳转  =================
        Intent pIntent = new Intent(Intent.ACTION_MAIN);
        pIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        pIntent.setComponent(new ComponentName(fragmentActivity.getPackageName(), LAUNCHER_CLASS.getCanonicalName()));
        pIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        fragmentActivity.startActivity(pIntent);
        // ===============================================
    }

    /**
     * 检查推送操作
     *
     * @param activity
     */
    private void checkJPushHandler(FragmentActivity activity) {
        if (activity != null) {
            try {
                // 判断是否点击推送消息 - 必须点击了才进行处理
                JPushBean jPushData = SPManager.JPushData.getJPushData();
                if (jPushData != null) {
                    // 获取推送消息ID
                    String pushMsgId = jPushData.pushMsgId;
                    // 获取下发通道
                    String romType = jPushData.romType;
                    String pushTitle = jPushData.pushTitle;
                    String pushContent = jPushData.pushContent;
                    String pushExtras = jPushData.pushExtras;
                    // 清空全部
                    SPManager.JPushData.clearJPushData();
                    Logger.e("jpushManager  is pushData set ");
                    // 判断是否处理
                    if (pushHandler != null) {
                        pushHandler.onPushHandler(activity, pushMsgId, romType, pushTitle, pushContent, pushExtras);
                    }
                } else {
                    Logger.e("jpushManager  is pushData null ");
                }
            } catch (Exception e) {
                Logger.e("jpushManager" + e.getMessage());
            }
        }
    }

    // == 对外提供方法 ==

    /**
     * 检查推送
     *
     * @param activity
     * @param value
     */
    public void checkJPush(FragmentActivity activity, String value) {
        if (pushHandler != null) {
            // 判断是否处理推送
            if (pushHandler.isHandlerPush(value)) {
                // 检查推送处理
                checkJPushHandler(activity);
            }
        }
    }

    /**
     * 获取跳转Intent
     *
     * @param context
     * @param pushMsgId   消息ID
     * @param romType     下发通道
     * @param pushTitle   消息标题
     * @param pushContent 消息内容
     * @param pushExtras  附加字段
     * @return
     */
    public Intent getOpenClickActivityIntent(Context context, String pushMsgId, String romType, String pushTitle, String pushContent, String pushExtras) {
        try {
            Intent intent = new Intent(context, OpenClickActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Bundle bundle = new Bundle();
            bundle.putString(KEY_MSGID, pushMsgId);
            bundle.putString(KEY_WHICH_PUSH_SDK, romType);
            bundle.putString(KEY_TITLE, pushTitle);
            bundle.putString(KEY_CONTENT, pushContent);
            bundle.putString(KEY_EXTRAS, pushExtras);
            intent.putExtras(bundle);
            return intent;
        } catch (Exception e) {
            Logger.e("jpushManager" + e.getMessage());
        }
        return null;
    }

    /**
     * 设置 android.intent.category.LAUNCHER 类
     *
     * @param launcherClass
     */
    public void setLauncherClass(Class launcherClass) {
        LAUNCHER_CLASS = launcherClass;
    }


    // 推送判断处理接口
    private JPushManager.JPushHandlerListener pushHandler;

    /**
     * 设置推送判断处理接口
     *
     * @param pushHandlers
     */
    public void setJPushHandlerListener(JPushHandlerListener pushHandlers) {
        pushHandler = pushHandlers;
    }

    /**
     * detail: 推送处理接口
     * Created by Ttt
     */
    public interface JPushHandlerListener {

        /**
         * 是否处理推送
         *
         * @param value
         * @return
         */
        boolean isHandlerPush(String value);

        /**
         * @param activity
         * @param pushMsgId 消息Id
         * @param romType   下发通道
         * @param nTitle    标题
         * @param nContent  内容
         * @param nExtras   通知附加字段
         */
        void onPushHandler(FragmentActivity activity, String pushMsgId, String romType, String nTitle, String nContent, String nExtras);
    }


}
